<template>
  <div class="h-full p-md">
    <div class="flex-between">
      <div class="flex gap-lg items-center">
        <el-segmented v-model="filterType" :options="filterOptions" @change="handleFilterChange"/>
        <el-select v-model="viewMode" placeholder="显示方式" style="width: 120px">
          <el-option label="列表显示" value="list"/>
          <el-option label="Grid显示" value="grid"/>
          <el-option label="Wrap显示" value="wrap"/>
          <el-option label="瀑布流" value="masonry"/>
        </el-select>
      </div>
      <el-button type="primary">新增</el-button>
    </div>

    <!-- 瀑布流模式 -->
    <MasonryWall
        v-if="viewMode === 'masonry' && !loading"
        :items="todos"
        :column-width="300"
        :gap="12"
        class="mt-md"
    >
      <template #default="{ item: todo }">
        <div class="todo-item p-lg cursor-pointer" @click="handleTodoClick(todo.id)">
          <!-- 第一行：时间、收藏 -->
          <div class="flex-between mb-sm">
            <span class="text-xs text-secondary">{{ formatDate(todo.createdTime) }}</span>
            <img
                v-if="todo.isFavorite"
                src="@/assets/images/icon/like.svg"
                alt="收藏"
                class="favorite-icon"
            />
          </div>

          <!-- 第二行：标题 -->
          <div class="todo-title font-bold text-primary mb-sm">
            {{ extractTitleAndContent(todo).title }}
          </div>

          <!-- 第三行：内容（瀑布流模式显示完整内容） -->
          <div v-if="extractTitleAndContent(todo).restContent" class="todo-content text-regular full-content">
            {{ extractTitleAndContent(todo).restContent }}
          </div>
        </div>
      </template>
    </MasonryWall>

    <!-- 其他显示模式 -->
    <div
        v-else
        v-loading="loading"
        class="mt-md"
        :class="{ 'todo-grid': viewMode === 'grid', 'todo-wrap': viewMode === 'wrap' }"
    >
      <div
          v-for="todo in todos"
          :key="todo.id"
          class="todo-item p-lg cursor-pointer"
          :class="{ 'mb-md': viewMode === 'list' }"
          @click="handleTodoClick(todo.id)"
      >
        <!-- 第一行：时间、收藏 -->
        <div class="flex-between mb-sm">
          <span class="text-xs text-secondary">{{ formatDate(todo.createdTime) }}</span>
          <img
              v-if="todo.isFavorite"
              src="@/assets/images/icon/like.svg"
              alt="收藏"
              class="favorite-icon"
          />
        </div>

        <!-- 第二行：标题 -->
        <div class="todo-title font-bold text-primary mb-sm">
          {{ extractTitleAndContent(todo).title }}
        </div>

        <!-- 第三行：内容（非瀑布流模式最多显示2行） -->
        <div v-if="extractTitleAndContent(todo).restContent" class="todo-content text-regular">
          {{ extractTitleAndContent(todo).restContent }}
        </div>
      </div>

      <el-empty v-if="todos.length === 0 && !loading" description="暂无数据"/>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, inject, watch, type Ref} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import MasonryWall from '@yeger/vue-masonry-wall'
import {getTodoList} from '../api'
import type {Todo} from '../types'
import {formatDate} from '@/utils/date'

const router = useRouter()
const route = useRoute()

const STORAGE_KEY = 'todo_view_mode'

const todos = ref<Todo[]>([])
const loading = ref(false)

// 提取标题和内容的辅助函数
const extractTitleAndContent = (todo: Todo) => {
  const content = todo.content || ''
  const firstLineEnd = content.indexOf('\n')

  if (firstLineEnd === -1) {
    // 没有换行符，整个内容作为标题
    return { title: content, restContent: '' }
  }

  const title = content.substring(0, firstLineEnd).trim()
  const restContentRaw = content.substring(firstLineEnd + 1)

  // 去掉空行：将内容按行分割，过滤掉空行，再重新组合
  const restContent = restContentRaw
    .split('\n')
    .filter(line => line.trim() !== '')
    .join('\n')

  return { title, restContent }
}

// 注入父组件提供的选中分类ID
const selectedCategoryId = inject<Ref<string | undefined>>('selectedCategoryId')

// 如果有 categoryId 参数，初始化为空字符串（不选中任何筛选）；否则为 'all'
const filterType = ref(route.query.categoryId ? '' : 'all')
const filterOptions = [
  {label: '全部', value: 'all'},
  {label: '收藏', value: 'favorite'}
]

// 从localStorage读取上次的显示方式，默认为'list'
const savedViewMode = localStorage.getItem(STORAGE_KEY) || 'list'
const viewMode = ref(savedViewMode)

const fetchTodos = async () => {
  loading.value = true
  try {
    const isFavorite = filterType.value === 'favorite' ? true : undefined
    todos.value = await getTodoList(selectedCategoryId?.value, isFavorite)
  } catch (error) {
    console.error('获取 Todo 列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleFilterChange = () => {
  // 如果点击"全部"或"收藏"，清除分类选中和路由参数
  if (filterType.value === 'all' || filterType.value === 'favorite') {
    selectedCategoryId!.value = undefined
    router.push({path: '/todo'})
  }
  fetchTodos()
}

const handleTodoClick = (todoId: string) => {
  router.push({
    path: `/todo/${todoId}`,
    query: route.query // 保留当前的查询参数（包括 categoryId）
  })
}

// 监听分类ID变化，清除筛选状态并重新获取待办列表
watch(
    () => selectedCategoryId?.value,
    (newValue) => {
      // 只有当选中了某个分类时（不是 undefined），才清除筛选状态
      if (newValue !== undefined) {
        filterType.value = '' // 清除筛选状态（既不是全部，也不是收藏）
      }
      fetchTodos()
    }
)

// 监听显示方式变化，保存到localStorage
watch(viewMode, (newMode) => {
  localStorage.setItem(STORAGE_KEY, newMode)
})

onMounted(() => {
  fetchTodos()
})
</script>

<style scoped>
.todo-item {
  background-color: #f8f8f8;
  border-radius: var(--radius-sm);
  transition: all 0.3s;
}

.todo-item:last-child {
  margin-bottom: 0 !important;
}

.todo-content {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  line-height: 1.5;
  white-space: pre-wrap;
  word-wrap: break-word;
  letter-spacing: 0.3px;
  font-size: 0.75rem;
}

.todo-content.full-content {
  display: block;
  -webkit-line-clamp: unset;
  overflow: visible;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.favorite-icon {
  width: 10px;
  height: 10px;
  cursor: pointer;
}

/* Grid 布局样式 */
.todo-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: var(--spacing-md);
  width: 100%;
  max-width: 100%;
  overflow: hidden;
}

.todo-grid .todo-item {
  margin-bottom: 0;
  min-width: 0;
  overflow: hidden;
}

/* Wrap 布局样式 */
.todo-wrap {
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-md);
}

.todo-wrap .todo-item {
  margin-bottom: 0;
  flex: 0 0 auto;
  max-width: 300px;
  min-width: 250px;
}
</style>
